import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux';
import {Tabs, Icon, message, Modal} from 'antd'
const TabPane = Tabs.TabPane;
import 'styles/corporate-payment-report/corporate-payment-report-detail.scss'
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service'
import baseService from "share/base.service";
import CorporatePaymentReportDetailAlert from './corporate-payment-report-detail-alert'
import CorporatePaymentReportDetailHeader from './corporate-payment-report-detail-header'

import SlideExpenseReportDetailHistory from './slide-expense-report-detail-history'
import SlideExpenseReportDetailBudget from './slide-expense-report-detail-budget'
import CorporatePaymentReportDetailBar from './corporate-payment-report-detail-bar'
import CorporatePaymentReportDetailPay from './corporate-payment-report-detail-pay'
import SlideExpenseReportDetailExpenseInvoice from 'containers/financial-management/new-finance-audit/slide-expense-report-detail/slide-expense-report-detail-expense/slide-expense-report-detail-expense-invoice'
import SubmitAndCheckResult from '../component/submit-and-check-result'
import expenseService from "containers/my-account/expense.service";
import ConcurrentMark from "containers/expense-report/template/concurrent-mark";
import SlideDocument from 'components/template/slide-document/slide-document'
import financeAuditService from 'containers/financial-management/new-finance-audit/finance-audit.service'
import SlideFrame from "share/openSlideFrame";
import NewExpenseReport from "../../new-corporate-payment-report";
import errorMessage from 'share/errorMessage';
import AuditTipsBottomFrame from "containers/financial-management/new-finance-audit/components/audit-tips/bottom-frame";
import expenseReportFunction from "containers/expense-report/expense-report.function";
import menuRoute from "routes/menuRoute";
import {getQueryUrlParam, messages} from "share/common";
import expenseReportService from "containers/expense-report/expense-report.service";

const { isApproveButtonsShow } = expenseReportFunction;
class CorporatePaymentReportDetail extends Component {

  state = {
    loading: true,
    info: {},
    form: {},
    applicant: {},
    creditScore: {},
    jobInfo: {},
    approvalHistory: [],
    approvalChains: [],
    invoiceEnabled: false,
    ocrEnabled: false,
    isAuditInApproveStatus: false,
    prendingAudit: false,
    auditCapability: false,
    templateCodeList: [],
    selectedExpense: [],
    expenseReportInvoices: [],
    failedInvoices: [],
    tableLoading: false,
    isWaitForAudit: false,
    isAuditEditable: false,
    isSupportSingleReject: false,
    activeTab: 'pay-info', //默认tab
    selectedInvoice: [],
    auditFlag: false,
    submitting: false,
    payInfoList: [] //付款行列表
  };

  afterCheckOrAuto = refreshType => {
    this.setState({ selectedExpense: [] });
    if (refreshType === 'receiptList') {
      this.setState({ selectedInvoice: [] });
      this.receiptRef.getInvoiceList();
    } else {
      this.getInfo(this.props);
    }
  };

  //redux中options默认是登录人的权限，单据审核权限应当取单据申请人的，因此当当前单据申请人不是登录人时，需要刷新权限配置
  componentWillMount() {
    const { user, loginUser, entry, tempUserOID, applicantOID } = this.props;
    const { options: { auditBaseConfig = {} } } = this.props;
    let loginUserOID = entry === 'invoice-bag-audit' ? tempUserOID : loginUser.userOID;
    if(loginUserOID !== (applicantOID || user.userOID)) {
      baseService.changeLoginInfo(applicantOID || user.userOID, true).then(res => {
        //登录人和单据申请人确实不是一个人，但应用在同一条规则下
        if(res[3].data.auditBaseConfig.baseConfigId === auditBaseConfig.baseConfigId) {
          this.getInfo(this.props);
        }
      });
      return;
    }
    this.getInfo(this.props);
  }

  componentWillReceiveProps(nextProps) {
    const { expenseReportOID, options: { auditBaseConfig: newAuditBaseConfig = {} }} = nextProps;
    const { options: { auditBaseConfig = {} } } = this.props;
    if((expenseReportOID && expenseReportOID !== this.props.expenseReportOID)) {
      this.getInfo(nextProps);
    }

    if((auditBaseConfig.baseConfigId !== newAuditBaseConfig.baseConfigId)) {
      this.getInfo(nextProps);
    }
  }

  //关闭侧拉框后需更新redux内options为当前登录人的
  componentWillUnmount() {
    const { user, loginUser, entry, tempUserOID, applicantOID } = this.props;
    let loginUserOID = entry === 'invoice-bag-audit' ? tempUserOID : loginUser.userOID;
    if(loginUserOID !== (applicantOID || user.userOID)) {
      baseService.changeLoginInfo(loginUserOID);
    }
  }

  getInfo = (props = this.props, refreshAll = true) => {
    const expenseReportOID = this.props.expenseReportOID || (this.props.params ? this.props.params.expenseReportOID : '');
    const { profile, close } = this.props;
    this.setState({ loading: true });
    expenseReportOID && corporatePaymentReportService.getCorporatePaymentReportDetail(expenseReportOID, { showNodeName: true }).then(res => {
      let expenseDetail = res.data.rows || {};

      if (profile['web.invoice.keep.consistent.with.expense']) {
        expenseDetail.currencySame = true;
      }
      if(refreshAll) {
        this.getBudgetExplainNumber(expenseDetail.id);
        this.getInvoiceOpenStatus();
        this.getAuditFlag(expenseDetail.expenseReportOID);
      }
      let costCenterItemsApportion = [];
      expenseDetail.custFormValues.map(field => {
        if (field.messageKey === 'select_cost_center') {
          if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
            costCenterItemsApportion.push({
              fieldName: field.fieldName,
              costCenterOID: JSON.parse(field.dataSource || '{}').costCenterOID,
              costCenterItemName: field.showValue,
              name: field.showValue,
              costCenterItemOID: field.value,
              required: field.required
            })
          }
        }
        if (field.messageKey === 'select_department') {
          if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
            costCenterItemsApportion.push({
              fieldName: field.fieldName,
              costCenterOID: '00000000-0000-0000-0000-000000000000',
              costCenterItemName: field.showValue,
              name: field.showValue,
              costCenterItemOID: field.value,
              required: field.required
            })
          }
        }
      });
      expenseDetail.costCenterItemsApportion = costCenterItemsApportion;
      this.setState({
        info: expenseDetail,
        loading: refreshAll
      }, () => refreshAll && this.getThirdInterface(props));
    }).catch(err => {
      console.log(err);
      errorMessage(err.response);
      setTimeout(close, 1000);
    });
  };

  getAuditFlag = entityOID => {
    financeAuditService.getAuditFlag({ entityOID, entityType: 1002 }).then(res => {
      this.setState({ auditFlag: res.data });
    })
  };

  getThirdInterface = props => {
    const { info } = this.state;
    const options = props.options || this.props.options;
    const { auditBaseConfig = {} } = options;
    const { status } = this.props.params;
    const { expenseReportOID, applicantOID, applicantJobId, setOfBooksId } = info;
    this.getUserInfo(applicantOID);
    this.getHistory();
    let thirdInterface = [
      corporatePaymentReportService.getFormInfo(expenseReportOID),
      applicantJobId && corporatePaymentReportService.getJobInfo(applicantJobId),
      corporatePaymentReportService.getAuditChain(expenseReportOID, 1002),
      baseService.getHonestInfo(applicantOID),
      corporatePaymentReportService.checkInvoice(expenseReportOID),
      status === 'prending_audit' && expenseService.getAccountFlag()
    ];
    Promise.all(thirdInterface).then(res => {
      let isAuditInApproveStatus = res[2].data.chainDTO && res[2].data.chainDTO.currentFlag && res[2].data.chainDTO.nodeType === 1012;
      let prendingAudit = res[2].data.prendingAudit;
      let entry = this.props.entry || this.props.params.entry;
      let isWaitForAudit = entry === 'audit' && this.checkNewAuth() &&
        ((info.status === 1003 && prendingAudit) || isAuditInApproveStatus);
      let isAuditEditable = isWaitForAudit && auditBaseConfig.reviewEditSuitable && auditBaseConfig.reviewEditEnable;
      let isSupportSingleReject = auditBaseConfig.reviewEditSuitable && auditBaseConfig.expenseBatchReject;
      this.setState({
        loading: status === 'prending_audit',
        form: res[0].data.rows || {},
        jobInfo: res[1] ? res[1].data || {} : {},
        isAuditInApproveStatus,
        prendingAudit,
        isWaitForAudit,
        isAuditEditable,
        creditScore: res[3].data,
        failedInvoices: res[4].data || [],
        isSupportSingleReject
      });
      return res[5];
    }).then(res => {
      res && res.data && expenseService.getCertificatePreviewTab(setOfBooksId).then(ledgerRes => {
        let templateCodeList = ledgerRes.data && Array.isArray(ledgerRes.data) ?
          ledgerRes.data.filter(i =>
            ((i.templateCode === 'GL_EXPENSE') && (i.isEnable === true)) ||
            ((i.templateCode === 'GL_WRITE_OFF') && (i.isEnable === true))
          ).map(i => i.templateCode) : [];
        this.setState({ templateCodeList, loading: false });
      }).catch(() => {
        this.setState({ loading: false })
      });
      !(res && res.data) && this.setState({ loading: false })
    }).catch(e => {
      console.log(e);
      this.setState({ loading: false })
    });
  };

  //获取员工信息
  getUserInfo = applicantOID => {
    baseService.getUserInfo(applicantOID).then(res => {
      this.setState({ applicant: res.data })
    })
  };

  getHistory = () => {
    const { info: { expenseReportOID, status } } = this.state;
    const { loginUser } = this.props;
    let entry = this.props.entry || this.props.params.entry;
    corporatePaymentReportService.getExpenseHistoryInfo(expenseReportOID).then(res => {
      let approvalChains = (res.data.rows || {}).approvalChains || [];
      let isWaitForApprove = isApproveButtonsShow(approvalChains, loginUser.userOID, status);
      let auditCapability = isWaitForApprove &&
        approvalChains.length > 0 && approvalChains[0].invoiceAllowUpdateType === 1 && (
        (entry === 'approve' && approvalChains[0].nodeType === 1001) ||
        (entry === 'audit' && approvalChains[0].nodeType === 1012)
      );
      this.setState({
        approvalHistory: (res.data.rows || {}).approvalHistoryDTOs || [],
        approvalChains,
        auditCapability,
        showApproveBottom: isWaitForApprove
      })
    })
  };

  //是否开通发票查验和OCR
  getInvoiceOpenStatus = () => {
    const { loginUser, params: { activeTab } } = this.props;
    expenseService.getTitleList(loginUser.userOID).then(res => {
      this.setState({
        invoiceEnabled: res.data.showCheckInvoiceFlag,
        ocrEnabled: res.data.showOCRFlag,
        activeTab: res.data.showOCRFlag && activeTab ? activeTab : this.state.activeTab
      })
    })
  };

  //获取预算执行结果数量
  getBudgetExplainNumber = id => {
    expenseReportService.getBudgetExplainCount({
      documentType: 'EXP_REPORT',
      documentId: id
    }).then(res => {
      this.setState({ budgetExplainNumber: res.data })
    })
  };

  onGetInvoice = expenseReportInvoices => {
    this.setState({ expenseReportInvoices });
  };

  onSelectExpense = selectedExpense => {
    this.setState({ selectedExpense });
  };

  getPayInfoList = payInfoList => this.setState({ payInfoList });

  getChildContext() {
    const {
      applicant, jobInfo, info, form,
      approvalHistory, auditCapability, ocrEnabled,
      approvalChains, invoiceEnabled, creditScore,
      isAuditInApproveStatus, prendingAudit,
      isWaitForAudit, isAuditEditable, isSupportSingleReject,
      showApproveBottom, expenseReportInvoices
    } = this.state;
    let entry = this.props.entry || this.props.params.entry;
    return {
      applicant,
      jobInfo,
      info,
      form,
      approvalHistory,
      auditCapability,
      approvalChains,
      ocrEnabled,
      invoiceEnabled,
      isAuditInApproveStatus,
      isWaitForAudit,
      creditScore,
      prendingAudit,
      isAuditEditable,
      isSupportSingleReject,
      entityType: 1002,
      entry,
      showApproveBottom,
      expenseReportInvoices
    }
  }

  onClickCollapse = () => {
    const { tableRefMap } = this.state;
    this.setState({ tableLoading: true }, () => {
      setTimeout(() => {
        tableRefMap && tableRefMap.length && tableRefMap.map(i => {
          const { tableRef, columns } = i;
          tableRef.refreshTableColumnsWidth(columns);
        });
        this.setState({ tableLoading: false });
      }, 301);
    });
  };

  onClickEditFields = () => {
    const { info, form, jobInfo, isAuditEditable } = this.state;
    SlideFrame.openSlideFrame({
      title: messages('finance-9.key24')/*编辑对公支付单*/,
      content: NewExpenseReport,
      params: {
        isAuditEditable,
        expenseReport: info,
        formDetail: form,
        jobInfo,
        applicantJobId: info.applicantJobId
      },
      hasFooter: false,
      afterClose: params => params && params.refresh && this.getInfo(info, false)
    }, this);
  };

  annotateService = () => {
    const { info } = this.state;
    return financeAuditService.getAnnotateByEntityOID(info.expenseReportOID, 'DOCUMENT');
  };

  goBack = isNeedRefreshList => {
    const { pageFrom } = this.props.params;
    const { close } = this.props;
    if (close) {
      close(isNeedRefreshList);
    } else {
      try {
        let backURL = menuRoute.getRouteItem('corporate-payment-report').url;
        if (pageFrom === 'quickView' || getQueryUrlParam('backUrlKey') === "approve-expense-report-quick-view")
          backURL = menuRoute.getRouteItem('approve-expense-report-quick-view', 'key').url;
        if (location.pathname.indexOf('admin-approve-expense-detail') > -1)
          backURL = menuRoute.getRouteItem('process-monitoring-platform', 'key').url;
        if (pageFrom === 'my')
          backURL = menuRoute.getRouteItem('corporate-payment-report').url;
        if (pageFrom === 'approve' || location.pathname.indexOf('approve-expense-report-detail') > -1)
          backURL = menuRoute.getRouteItem('to-be-approve').url + `?tab=${location.search.indexOf('approvePending') > -1 ? 'approvePending' : 'approved'}`;
        if (pageFrom === 'scan-gun-view')
          backURL = menuRoute.getRouteItem('scan-gun-view').url.replace(':pageFrom', 'vendorPayment');
        if (pageFrom === 'entry')
          backURL = menuRoute.getRouteItem('entry-information').url;
        if (pageFrom === 'amortization')
          backURL = menuRoute.getRouteItem('amortization-management').url;
        this.context.router.push(backURL);
      } catch(e){
        console.log('原跳转逻辑失败，使用新跳转逻辑')
        menuRoute.goBack(this)
      }
    }
  };

  renderTabBarExtra = () => {
    const { language } = this.props;
    const { auditFlag } = this.state;
    const auditAlert = (
      <div className="slide-expense-report-detail-right-audit-ing">
        <Icon type="clock-circle" /> {messages('finance-9.key25')/*自动审核中请等待*/}
      </div>
    );
    // const auditTip = <AuditTipsButton from="auditDetail" />;
    const auditTip = null;
    if (auditFlag && language.code === 'zh_cn') {
      return <div>{auditAlert} {auditTip}</div>;
    } else if (auditFlag) {
      return auditAlert;
    } else if ( language.code === 'zh_cn') {
      return auditTip;
    } else {
      return null;
    }
  };

  render() {
    const {
      loading, info, approvalChains, isAuditInApproveStatus,
      selectedExpense, failedInvoices, expenseReportInvoices, ocrEnabled,
      isWaitForAudit, isAuditEditable, activeTab, selectedInvoice, auditFlag,
      submitting, payInfoList, budgetExplainNumber
    } = this.state;
    const { close, company, loginUser, params, language, approverOID } = this.props;
    let tab = this.props.tab || this.props.params.tab || getQueryUrlParam('status');
    let entry = this.props.entry || this.props.params.entry;
    let readOnly = this.props.readOnly || this.props.params.readOnly || getQueryUrlParam('readOnly') === 'true';
    return (
      <SlideDocument
        loading={loading}
        className='corporate-payment-report-detail'
        onClickCollapse={this.onClickCollapse}
        fieldsParams={{
          annotateService: this.annotateService,
          annotateDisabled: !isWaitForAudit,
          showEdit: info.status === 1001 || isAuditEditable,
          showBookDate: entry === 'audit',
          onClickEdit: this.onClickEditFields,
          company: company,
          user: loginUser,
          refreshInfo: this.getInfo,
        }}
        left={
          <div>
            <CorporatePaymentReportDetailAlert />
            <CorporatePaymentReportDetailHeader />
          </div>}
        right={<div className="slide-expense-report-detail-right">
          <Tabs
            activeKey={activeTab}
            tabBarExtraContent={this.renderTabBarExtra()}
            className="right-tabs"
            onChange={activeTab => this.setState({ activeTab, selectedExpense: [], selectedInvoice: [] })}
          >
            <TabPane tab={messages('finance-9.key26')/*付款信息*/} key='pay-info'>
              <CorporatePaymentReportDetailPay
                refreshInfo={this.getInfo}
                refreshPayInfoList={this.getPayInfoList}
              />
            </TabPane>
            {
              ocrEnabled && entry === 'audit' &&
              <TabPane tab={messages('finance-9.key27')/*发票模式*/} key='invoice'>
                <SlideExpenseReportDetailExpenseInvoice
                  ref={ref => this.receiptRef = ref}
                  selectedInvoice={selectedInvoice}
                  showOCRFlag={ocrEnabled}
                  expenseReportInvoices={expenseReportInvoices}
                  onSelectInvoice={selectedInvoice => this.setState({ selectedInvoice })}
                  refreshInfo={this.getInfo}
                  goBack={close}
                />
              </TabPane>
            }
            {budgetExplainNumber > 0 && (
              <TabPane tab={messages('expense-14.key303')/*预算执行*/} key='budget'>
                <SlideExpenseReportDetailBudget />
              </TabPane>
            )}
            {
              (
                ('' + info.status + info.rejectType !== '10011000') &&
                ('' + info.status + info.rejectType !== '10010')
              ) &&
              <TabPane tab={messages('finance-9.key28')/*审批历史*/} key='history'>
                <SlideExpenseReportDetailHistory />
              </TabPane>
            }
          </Tabs>
          {/*多级审核审核并发标记 || 审批流审批并发标记*/}
          {entry === 'audit' || entry === 'approve' && (
            <ConcurrentMark
              entityOID={params.expenseReportOID}
              approvalChains={approvalChains}
              isAuditInApproveStatus={isAuditInApproveStatus}
              style={{top: 4, right: 0}}
            />
            )}
          <SubmitAndCheckResult
            onRef={ref => this.submitRef = ref}
            expenseReportInvoices={expenseReportInvoices}
            payInfoList={payInfoList}
            onGetInvoice={this.onGetInvoice}
            getInfo={this.getInfo}
            goBack={this.goBack}
            tab={tab} //待审核 或待审批
          />
        </div>}
        bar={<CorporatePaymentReportDetailBar
          selectedExpense={selectedExpense}
          selectedInvoice={selectedInvoice}
          expenseReportInvoices={expenseReportInvoices}
          failedInvoices={failedInvoices}
          afterCheckOrAuto={this.afterCheckOrAuto}
          onSelectExpense={this.onSelectExpense}
          getHistory={this.getHistory}
          approverOID={approverOID}
          submitting={submitting}
          handleSubmit={this.submitRef && this.submitRef.handleSubmit}
          goBack={this.goBack}
          tab={tab}
          readOnly={readOnly}
        />}
        tipsFrame={auditFlag && language.code === 'zh_cn' ?
          <AuditTipsBottomFrame from="auditDetail" style={{ bottom: 78, zIndex: 10 }} /> : null}
      />
    )
  }

  static propTypes = {
    expenseReportOID: PropTypes.string
  };

  static childContextTypes = {
    applicant: PropTypes.object,
    jobInfo: PropTypes.object,
    info: PropTypes.object,
    form: PropTypes.object,
    approvalHistory: PropTypes.array,
    auditCapability: PropTypes.bool,
    approvalChains: PropTypes.array,
    ocrEnabled: PropTypes.bool,
    invoiceEnabled: PropTypes.bool,
    isAuditInApproveStatus: PropTypes.bool,
    isWaitForAudit: PropTypes.bool,
    creditScore: PropTypes.object,
    prendingAudit: PropTypes.bool,
    isAuditEditable: PropTypes.bool,
    isSupportSingleReject: PropTypes.bool,
    entityType: PropTypes.number,
    entry: PropTypes.string,
    showApproveBottom: PropTypes.bool,
    expenseReportInvoices: PropTypes.array
  }

}

let mapStateToProps = state => {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser,
    options: state.login.options,
    language: state.main.language
  }
};

CorporatePaymentReportDetail.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(CorporatePaymentReportDetail);
